//
//  MapVC.m
//  ImGuider
//
//  Created by llt on 2017/4/11.
//  Copyright © 2017年 imguider. All rights reserved.
//

#import "MapVC.h"
#import "MKMapView+ZoomLevel.h"

#import "UIView+Gradient.h"

#import "ScenicDescribeVC.h"
#import "TourMapVC.h"

#import "IGAnnotation.h"
#import "ViewAnnView.h"

#import "CityTourCardVC.h"
#import "ScenicSpotViewController.h"
#import "JMHoledView.h"

#import "ClusterAnnView.h"

static CGFloat minimunZoomARC = 0.0001;
static CGFloat annotatonGrgionPadFactor = 1.15;
static CGFloat maxDefreesARC = 360;

@interface MapVC ()<ViewAnnViewDelegate, MKMapViewDelegate>

@property (weak, nonatomic) IBOutlet MKMapView *mapView;
@property (weak, nonatomic) IBOutlet UIView *lineView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *lineViewTop;

@property (strong, nonatomic) KPClusteringController *clusteringController;

@property (nonatomic, strong) NSArray *viewsArray;

@property (nonatomic, strong) NSArray *linesArray;

@property (nonatomic, strong) NSArray *merchantArray;

@end

@implementation MapVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupUI];
    [self setupMapData];
}

- (void)dealloc {
    [_mapView removeAnnotations:_mapView.annotations];
    [_mapView removeFromSuperview];
}

- (void)setupUI {
    
    self.lineViewTop.constant = kNavigationBarHeight + 20;

    [self setNavBlackGradient];
    
    CLLocationCoordinate2D location = CLLocationCoordinate2DMake(self.city.lat.floatValue, self.city.lng.floatValue);
    
    [self.mapView setCenterCoordinate:transformFromWGSToGCJ(location, self.city.country) zoomLevel:kZoomLevel animated:YES];
}

#pragma mark --弹出菜单按钮 快速链接到景点  城市线路（还未确定）
//- (void)createMenuBtn {
//
//    DWBubbleMenuButton *MenuView = [[DWBubbleMenuButton alloc] initWithFrame:CGRectMake(kScreenWidth - 50,64,self.menuBtn.bounds.size.width,self.menuBtn.bounds.size.height)expansionDirection:DirectionDown];
//    MenuView.homeButtonView = self.menuBtn;
//    //MenuView.backgroundColor = [UIColor redColor];
//    [MenuView addButtons:[self createButtonArray]];
//
//    [self.view addSubview:MenuView];
//
//}
//
//- (NSArray *)createButtonArray {
//
//
//    NSMutableArray *buttonsMutable = [[NSMutableArray alloc] init];
//
//    for (NSString * str in self.city.tagsArray) {
//
//        if ([str isEqualToString:@"view"] || [str isEqualToString:@"line"] ) {
//            UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
//            if ([str isEqualToString:@"view"]) {
//                [button setImage:[UIImage imageNamed:@"ScenicSpot_btn"] forState:UIControlStateNormal];
//                button.tag = 100;
//            }else {
//                [button setImage:[UIImage imageNamed:@"map_tour_btn"] forState:UIControlStateNormal];
//                button.tag = 200;
//            }
//
//            button.frame = CGRectMake(0.f, 0.f, 30.f, 30.f);
//            button.layer.cornerRadius = button.frame.size.height / 2.f;
//            button.clipsToBounds = YES;
//            [button addTarget:self action:@selector(goDetailVC:) forControlEvents:UIControlEventTouchUpInside];
//
//            [buttonsMutable addObject:button];
//        }
//    }
//
//
//    return [buttonsMutable copy];
//}
//
//-(void)goDetailVC:(UIButton *)sender {
//
//    if (sender.tag == 100) {
//
//        ScenicSpotViewController * scenicSpotVC = [[ScenicSpotViewController alloc] init];
//        scenicSpotVC.city = self.city;
//        scenicSpotVC.title = MYLocalizedString(@"SITELIST_TITLE", nil);
//        [self.navigationController pushViewController:scenicSpotVC animated:YES];
//
//    }else if(sender.tag == 200){
//
//        CityTourCardVC * vc = [[CityTourCardVC alloc] init];
//
//        vc.cityID = self.city.cid;
//        vc.title = MYLocalizedString(@"CITYTOURLIST_TITLE", nil);
//        [self.navigationController pushViewController:vc animated:YES];
//    }
//
//}
//- (UIButton *)menuBtn {
//    if (!_menuBtn) {
//        UIButton * menuBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//
//        menuBtn.frame = CGRectMake(0,0, 40, 40);
//
//        _menuBtn = menuBtn;
//
//        [menuBtn setImage:[UIImage imageNamed:@"upMenu"] forState:UIControlStateNormal];
//
//        [menuBtn setImage:[UIImage imageNamed:@""] forState:UIControlStateSelected];
//        menuBtn.userInteractionEnabled = NO;
//        //[menuBtn addTarget:self action:@selector(showMoreBtn:) forControlEvents:UIControlEventTouchUpInside];
//    }
//
//    return _menuBtn;
//}
- (IBAction)showLine:(id)sender {
    
    TourMapVC *tourVC = [TourMapVC new];
    
    [tourVC show:self];
    
    tourVC.lineArray = self.linesArray;
}

- (void)newGuidePage {
    
    BOOL hasCitytour = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasCitytour"];
    BOOL hasScenic = [[NSUserDefaults standardUserDefaults] boolForKey:@"hasScenic"];
    
    if ((hasCitytour || self.linesArray.count == 0) && (hasScenic || self.viewsArray.count == 0)) {
        return;
    }
    
    //添加遮罩指示
    JMHoledView *holedView = [[JMHoledView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    [self.view.window addSubview:holedView];
    
    UIWindow *window = [[[UIApplication sharedApplication] delegate] window];
    
    if (!hasCitytour && self.linesArray.count > 0) {
        
        CGRect rect = [self.lineView convertRect:self.lineView.bounds toView:window];
        
        UIImageView *tourBGImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"map_tour_btn_bg"]];
        
        //        tourBGImageView.frame = CGRectMake(kScreenWidth, 60, 65, 54);
        
        [holedView addHCustomView:tourBGImageView onRect:rect];
        
        UIImageView *btnImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"map_tour_btn"]];
        [tourBGImageView addSubview:btnImageView];
        
        [btnImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            
            make.top.equalTo(tourBGImageView.mas_top).offset(2);
            make.bottom.equalTo(tourBGImageView.mas_bottom).offset(-2);
            make.left.equalTo(tourBGImageView.mas_left).offset(2);
            
            make.width.mas_equalTo(50);
        }];
        
        
        UIImage *guideImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_MAP_CITY_TOUR", nil)];
        
        UIImageView *imageview = [[UIImageView alloc] initWithImage:guideImage];
        
        CGRect guideRect = CGRectMake(CGRectGetMidX(rect) - guideImage.size.width , CGRectGetMaxY(rect) + 10, guideImage.size.width, guideImage.size.height);
        
        [holedView addHCustomView:imageview onRect:guideRect];
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasCitytour"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    
    
    __block NSInteger scenicIndex = -1;
    
    ViewAnnView *annView = nil;
    CGRect scenicRect = CGRectMake(kScreenWidth / 2, (kScreenHeight - 50) / 2, 42, 50);
    
    if (!hasScenic && self.viewsArray.count > 0) {
        
        annView = [[ViewAnnView alloc] init];
        
        Scenic *scenic = self.viewsArray[0];
        IGAnnotation *annotation = [[IGAnnotation alloc]init];
        
        CLLocationCoordinate2D location = CLLocationCoordinate2DMake(scenic.lat.doubleValue, scenic.lng.doubleValue);
        
        annotation.coordinate = location;
        annotation.title = scenic.viewname;
        
        annotation.infos = @{IGAnnotationImageKey:scenic.pictureArray.firstObject};
        
        annView.annotation = annotation;
        
        scenicIndex = [holedView addHCustomView:annView onRect:scenicRect];
        
        UIImage *guideImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_MAP_SCENIC", nil)];
        
        UIImageView *imageview = [[UIImageView alloc] initWithImage:guideImage];
        
        CGRect guideRect = CGRectMake(CGRectGetMidX(scenicRect) - guideImage.size.width / 2.0f , CGRectGetMaxY(scenicRect) + 10, guideImage.size.width, guideImage.size.height);
        
        [holedView addHCustomView:imageview onRect:guideRect];
        
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"hasScenic"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        __block BOOL secondStep = NO;
        
        @weakify(annView);
        annView.clickScenicViewBlock = ^{
            @strongify(annView);
            
            if (secondStep) {
                return;
            }
            
            secondStep = YES;
            
            annView.userInteractionEnabled = NO;
            
            [holedView removeHoles];
            
            [holedView addHCustomView:annView onRect:scenicRect];
            
            for (UIButton *btn in annView.subviews) {
                
                if (![btn isKindOfClass:[UIButton class]]) {
                    continue;
                }
                
                if (btn.tag == Tractfic) {
                    
                    UIImage *guideImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_MAP_SCENIC_NAV", nil)];
                    
                    UIImageView *imageview = [[UIImageView alloc] initWithImage:guideImage];
                    
                    CGRect guideRect = CGRectMake(CGRectGetMinX(scenicRect), CGRectGetMinY(scenicRect) - guideImage.size.height - 60, guideImage.size.width, guideImage.size.height);
                    
                    [holedView addHCustomView:imageview onRect:guideRect];
                    
                } else if (btn.tag == Intro) {
                    
                    UIImage *guideImage = [UIImage imageNamed:MYLocalizedString(@"GUIDE_MAP_SCENIC_DETAIL", nil)];
                    
                    UIImageView *imageview = [[UIImageView alloc] initWithImage:guideImage];
                    
                    CGRect guideRect = CGRectMake(CGRectGetMinX(scenicRect) - guideImage.size.width - 60, CGRectGetMinY(scenicRect) - guideImage.size.height, guideImage.size.width, guideImage.size.height);
                    
                    if (guideRect.origin.x < 8) {
                        guideRect.origin.x = 8;
                    }
                    
                    [holedView addHCustomView:imageview onRect:guideRect];
                }
            }
            
            scenicIndex = -1;
        };
        
    }
    
    [holedView clickedBlock:^(JMHoledView *holedView, NSInteger index) {
        
        if (scenicIndex == -1) {
            [holedView removeFromSuperview];
        } else {
            [annView showCallView];
        }
    }];
    
}

- (void)setupMapData {
    
    self.title = self.city.smartName;
    
    [ActivityIndicatorView showHUDAddedTo:self.view];
    
    
    dispatch_group_t net_group = dispatch_group_create();
    dispatch_group_enter(net_group);
    
    @weakify(self);
    [NetAPIManager getAllViewsWithCity:self.city.cid start:@(0) count:@(0) block:^(NSArray *viewsArray, NSError *error) {
        
        @strongify(self);
        
        [ActivityIndicatorView hideHUDAddedTo:self.view];
        // 获取地图上所有的大头针数据模型
        self.viewsArray = viewsArray;
        
        dispatch_group_leave(net_group);
    }];
    
    dispatch_group_enter(net_group);
    [NetAPIManager getAllBusinessWithCityid:self.city.cid.stringValue block:^(NSArray *businessArray, NSError *error) {
        
        @strongify(self);
        self.merchantArray = businessArray;
        
        dispatch_group_leave(net_group);
    }];
    
    dispatch_group_enter(net_group);
    [NetAPIManager getAllLinesBy:self.city.cid start:@(0) count:@(0) block:^(NSArray *linesArray, NSError *error) {
        @strongify(self);
        self.linesArray = linesArray;
        
        dispatch_group_leave(net_group);
        if (linesArray.count > 0) {
            self.lineView.hidden = NO;
        }
    }];
    dispatch_group_notify(net_group, dispatch_get_main_queue(), ^{
        [self newGuidePage];
        
        
        NSMutableArray *annArray = [NSMutableArray array];
        
        for (int i = 0; i < self.viewsArray.count; i ++) {
            Scenic *scenic = self.viewsArray[i];
            IGAnnotation *annotation = [[IGAnnotation alloc]init];
            annotation.type = MerchantTypeJingdian;
            
            CLLocationCoordinate2D location = CLLocationCoordinate2DMake(scenic.lat.doubleValue, scenic.lng.doubleValue);
            
            annotation.coordinate = transformFromWGSToGCJ(location, self.city.country);
            annotation.title = scenic.viewname;
            
            annotation.infos = @{IGAnnotationImageKey : scenic.pictureArray.firstObject, IGAnnotationIndexKey : @(i)};
            
            [annArray addObject:annotation];
        }
        
        for (int i = 0; i < self.merchantArray.count; i ++) {
            
            MerchantModel *model = self.merchantArray[i];
            IGAnnotation *annotation = [[IGAnnotation alloc]init];
            
            if ([model.type isEqualToString:@"shop"]) {
                annotation.type = MerchantTypeShangchang;
            } else if ([model.type isEqualToString:@"restaurant"]) {
                annotation.type = MerchantTypeCanyin;
            }
            
            CLLocationCoordinate2D location = CLLocationCoordinate2DMake(model.lat.doubleValue, model.lng.doubleValue);
            
            annotation.coordinate = transformFromWGSToGCJ(location, self.city.country);
            annotation.title = model.name;
            
            annotation.infos = @{IGAnnotationImageKey : model.pictureArray.firstObject, IGAnnotationIndexKey : @(i)};
            
            [annArray addObject:annotation];
        }
        
        if (annArray.count > 0) {
            
            KPGridClusteringAlgorithm *algorithm = [KPGridClusteringAlgorithm new];
            algorithm.annotationSize = CGSizeMake(42, 50);
            algorithm.clusteringStrategy = KPGridClusteringAlgorithmStrategyTwoPhase;
            
            self.clusteringController = [[KPClusteringController alloc] initWithMapView:self.mapView
                                                                    clusteringAlgorithm:algorithm];
            
            self.clusteringController.animationOptions = UIViewAnimationOptionCurveEaseOut;
            
            [self.clusteringController setAnnotations:annArray];
            [self zoomMapViewToFitAnnotations:annArray animated:YES];
        }
    });
}

- (void)zoomMapViewToFitAnnotations:(NSArray *)annotations animated:(BOOL)animated {
    
    NSInteger count = [annotations count];
    if ( count == 0) { return; } //bail if no annotations
    MKMapPoint points[count];
    for( int i=0; i < count; i++ ) {
        
        CLLocationCoordinate2D coordinate = [(id <MKAnnotation>)[annotations objectAtIndex:i] coordinate];
        points[i] = MKMapPointForCoordinate(coordinate);
    }
    
    MKMapRect mapRect = [[MKPolygon polygonWithPoints:points count:count] boundingMapRect];
    
    MKCoordinateRegion region = MKCoordinateRegionForMapRect(mapRect);
    
    region.span.latitudeDelta  *= annotatonGrgionPadFactor;
    region.span.longitudeDelta *= annotatonGrgionPadFactor;
    
    if( region.span.latitudeDelta > maxDefreesARC ) { region.span.latitudeDelta  = maxDefreesARC; }
    if( region.span.longitudeDelta > maxDefreesARC ){ region.span.longitudeDelta = maxDefreesARC; }
    
    if( region.span.latitudeDelta  < minimunZoomARC ) { region.span.latitudeDelta  = minimunZoomARC; }
    if( region.span.longitudeDelta < minimunZoomARC ) { region.span.longitudeDelta = minimunZoomARC; }
    
    if( count == 1 ) {
        region.span.latitudeDelta = 0.014;
        region.span.longitudeDelta = 0.014;
    }
    
    [self.mapView setRegion:region animated:animated];
}

#pragma mark - MKMapViewDelegate

- (nullable MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {
    
    if ([annotation isKindOfClass:[KPAnnotation class]]) {
        
        KPAnnotation *pin = (KPAnnotation *)annotation;
        
        if (pin.isCluster) {
            
            ClusterAnnView *clusterView = (ClusterAnnView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"clusterView"];
            if (!clusterView) {
                clusterView = [[ClusterAnnView alloc] initWithAnnotation:pin reuseIdentifier:@"clusterView"];
            }
            [clusterView setClusterText:@(pin.annotations.count).stringValue];
            
            return clusterView;
            
        }
        
        ViewAnnView *customView = (ViewAnnView *)[mapView dequeueReusableAnnotationViewWithIdentifier:@"customView"];
        
        if (!customView){
            
            customView =[[ViewAnnView alloc] initWithAnnotation:[pin.annotations anyObject] reuseIdentifier:@"customView"];
            customView.delegate = self;
        }
        customView.annotation = [pin.annotations anyObject];
        
        return customView;
    }
    
    return nil;
}

- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated {
    
    [self.clusteringController refresh:YES];
}

- (IBAction)resetMapCenter:(id)sender {
    
    CLLocationCoordinate2D center = transformFromWGSToGCJ(CLLocationCoordinate2DMake(self.city.lat.floatValue, self.city.lng.floatValue), self.city.country);
    MKCoordinateSpan span = self.mapView.region.span;
    
    if (CLLocationCoordinate2DIsValid(center)) {
        
        if ([IGUtil getDistanceFromCoordinate:center toCoordinate:self.mapView.userLocation.coordinate] < 3000) {
            
            [self.mapView setRegion:MKCoordinateRegionMake(self.mapView.userLocation.coordinate, span) animated:YES];
        } else {
            
            [self.mapView setRegion:MKCoordinateRegionMake(center, span) animated:YES];
        }
    }
}

#pragma mark -IGAnnotationViewDelegatge
- (void)annotationView:(KPAnnotation *)pin clickBtn:(ClickBtnType) btnType {
    
    IGAnnotation *ann = [pin.annotations anyObject];
    
    switch (btnType) {
        case Intro: { //简介
            
            if (ann.type != MerchantTypeJingdian) {
                return;
            }
            
            Scenic *scenic = self.viewsArray[[ann.infos[IGAnnotationIndexKey] integerValue]];
            ScenicDescribeVC *scenicDesVC = [ScenicDescribeVC new];
            scenicDesVC.scenicid = scenic.ID;
            [self.navigationController pushViewController:scenicDesVC animated:YES];
        }
            break;
        case Tractfic: {// 交通
            
            [IGUtil tractficToLocation:ann.coordinate vc:self];
        }
            break;
            
        case ShowList: {// 显示列表
            
            
            if (ann && [ann isKindOfClass:[IGAnnotation class]]) {
                
                MerchantModel *model = self.merchantArray[[ann.infos[IGAnnotationIndexKey] integerValue]];
                
                TourMapVC *tourVC = [TourMapVC new];
                [tourVC show:self];
                
                tourVC.model = model;
                
                return;
            }
        }
            
        default:
            break;
    }
}

@end

